package com.heartbeat.util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

public class ConnectionProxy {

	private static ConnectionProxy proxy = new ConnectionProxy();
	
	private static Map<String, Integer> proxyMap = new HashMap<String, Integer>();
	
	private static int count=0;
	
	//private static boolean  hasError = false;
	
	public static ConnectionProxy getInstance(){
		return proxy;
	}
	
	private ConnectionProxy(){}
	
	private static String ip="202.171.253.98";
	private static int port=80;
	static{
		proxyMap.put("211.142.236.136", 80);
		proxyMap.put("123.125.116.243", 21238);
		proxyMap.put("218.2.51.72", 8090);
		proxyMap.put("218.188.13.237", 8888);
		proxyMap.put("86.96.229.123", 80);
		proxyMap.put("122.72.99.3", 80);
		proxyMap.put("178.18.17.250", 8089);
		proxyMap.put("86.96.229.68", 8888);
		proxyMap.put("199.231.93.102", 7808);
		proxyMap.put("222.73.242.137", 80);
		proxyMap.put("69.197.132.68", 7808);
	
	}
	
	public URLConnection getConnection(String webUrl) throws IOException{
		URLConnection con = null;
		
		URL url = new URL(StringUtils.trim(webUrl));
		
		int size=proxyMap.size();
		int maxSize = size+2;
		int index=(int)Math.round(Math.random()*maxSize);
		//System.out.println("index="+index);
		
		//con = url.openConnection();
		if(index > size-1){
			con = url.openConnection();
		}else{
			//if(hasError){
				Object[] proxyArray = proxyMap.keySet().toArray();
				ip = (String)proxyArray[index];
				port=proxyMap.get(ip);
			//}
			//System.out.println("haseError=" + hasError +";ip=" + ip +"; port=" + port);
			SocketAddress addr = new InetSocketAddress(ip,port);
			Proxy typeProxy = new Proxy(Proxy.Type.HTTP, addr);
			con = url.openConnection(typeProxy);
			
			count++;
		}
		
		return con;
	}
}
